import {deepFullCopy, messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Spin, Row, Col, Icon, message, Checkbox, Button, Popover } from 'antd'
import Condition from 'components/condition'
import 'styles/components/template/business-card-consumption-selector.scss'
import baseService from 'share/base.service'
import moment from 'moment'

const { If, Else } = Condition;

class BusinessCardConsumptionSelector extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      consumptionRecords: [],
      page: 0,
      pageSize: 10,
      selectedSum: 0,
      hasMore: true,
      checkedAmount: 0, // 入账币种的总金额
      checkedOriAmount: 0, // 原币种的总金额
      oriCurCod: '', // 原币种
      checkedNum: 0,
      businessCardLoading: true,
      cardList: []
    };
  }

  componentDidMount(){
    this.getList();
  }

  componentWillReceiveProps(nextProps){}

  //得到上个月的账单日.上个月不肯能是1号和28号以后，所以不用计算月末，日期直接-1即可
  getLastMonthBillDate = (billDate) => {
    let date = new Date(billDate);
    let thisYear = date.getFullYear();
    let thisMonth = date.getMonth() + 1;
    let lastMonth = thisMonth === 1 ? 12 : (thisMonth - 1);
    let lastDate = date.getDate() + 1;
    let lastYear = lastMonth === 12 ? (thisYear - 1) : thisYear;
    lastMonth = lastMonth < 10 ? `0${lastMonth}` : lastMonth;
    lastDate = lastDate < 10 ? `0${lastDate}` : lastDate;
    let returnDate = `${lastYear}-${lastMonth}-${lastDate}`;
    return new Date(returnDate).format('yyyy-MM-dd');
  };

  getList = () => {
    let { page, pageSize ,selectedSum} = this.state;
    const { businessCardConsumptions, singleBusinessCards } = this.props;
    this.setState({ loading: true });
    baseService.getBusinessCardConsumptionList('CMBC', false, this.props.ownerOID || this.props.user.userOID, page, pageSize, undefined, this.props.invoiceOID, this.props.isDidi).then(res => {
      if(res.data.success){
        let records = res.data.rows;
        let consumptionRecords = this.state.consumptionRecords;
        records.map(record => { // records：所有的公务卡数据 businessCardConsumptions：用户选中的公务卡数据
          if (!record.relationMap) {
            record.relationMap = {}
          }
          if (!record.relationMap.WAIT) {
            record.relationMap.WAIT = []
          }
          record.relationMap.WAIT.push({
            oriCod: record.oriCurCod,
            oriAmount: record.oriRemainAmt,
            amount: record.remainAmt || 0,
            atlBankTransactionId: record.id,
            checked: false
          })
          if (record.relationMap) {
            const keys = Object.keys(record.relationMap) // 获取公务卡明细的所有状态，如：['NONE', 'INVOICE']
            keys.map((key, keyIndex) => {
              record.relationMap[key].map((relation, relationIndex) => {
                relation.checked = false
                businessCardConsumptions.some((selectedRecord, selectedRecordIndex) => {
                  let finish = false
                  if (selectedRecord.id === record.id) {
                    record.oriCurInvoiceAmt = selectedRecord.oriCurInvoiceAmt || 0
                    record.curInvoiceAmt = selectedRecord.curInvoiceAmt || 0
                  }
                  if (!selectedRecord.relationMap) {
                    selectedRecord.relationMap = {}
                  }
                  if (selectedRecord.relationMap[key]) {
                    selectedRecord.relationMap[key].some((selectedRelation, selectedRelationIndex) => {
                      if (['INVOICE', 'NONE'].includes(key)) {
                        if (selectedRelation.checked && selectedRelation.id === relation.id && selectedRelation.amount !== 0) {
                          relation.checked = true
                          finish = true
                        }
                      }
                      if (key === 'WAIT') {
                        if (selectedRelation.checked && selectedRecord.id === record.id && selectedRelation.amount !== 0) {
                          relation.checked = true
                          finish = true
                        }
                      }
                      return finish
                    })
                  }
                  return finish
                })
              })
            })
          }
          record.showDetails = record.showDetails || false
          let groupLength = consumptionRecords.length;
          /**
           * return 0 // 待拆分、已拆分、已关联公务卡明细数量为0
           * return 1 // 已勾选数量为0
           * return 2 // 待拆分、已拆分、已关联公务卡明细被全选
           * return 3 // 部分勾选
           */
          const checkedRes = this.validateAllChecked(record)
          switch (checkedRes) {
            case 0:
            case 1:
            case 3:
              record.checked = false
              break
            case 2:
              record.checked = true
              break
          }
          // if(groupLength === 0 || consumptionRecords[groupLength - 1].endDate !== record.bilDate){
          //   let startDate = this.getLastMonthBillDate(record.bilDate);
          //   let consumptionRecord = {
          //     endDate: record.bilDate,
          //     month: new Date(record.bilDate).getMonth() + 1,
          //     startDate,
          //     records: [],
          //     checked: false
          //   };
          //   consumptionRecord.records.push(record);
          //   consumptionRecords.push(consumptionRecord);
          // } else {
          //   consumptionRecords[groupLength - 1].records.push(record);
          // }
          /**
           * 2021-01-19 去掉前端对于公务卡数据的按照月份排序逻辑
           * 由于consumptionRecords的结构牵扯过多，所以保留了consumptionRecords的原有结构
           */
          if (!consumptionRecords[0] || !consumptionRecords[0].records) {
            consumptionRecords[0] = {
              records: [],
              checked: false
            }
          }
          consumptionRecords[0].records.push(record)
        });
        this.setState({
          consumptionRecords,
          page: page + 1,
          hasMore: records.length !== 0 && records.length % pageSize === 0,
          selectedSum,
        }, () => {
          this.countRecords()
        })
      }
      this.setState({ loading: false });
    })
  }

  handleCheckGroup = (groupIndex) => {
    let { consumptionRecords, selectedSum } = this.state;
    let target = !consumptionRecords[groupIndex].checked;
    consumptionRecords[groupIndex].checked = target;
    consumptionRecords[groupIndex].records.map(record => {
      record.checked = target;
      return record;
    });
    let length = consumptionRecords[groupIndex].records.length;
    selectedSum += target ? length : -length;
    this.setState({ consumptionRecords, selectedSum })
  };

  handleCheckItem = (groupIndex, index) => {
    let { consumptionRecords, selectedSum } = this.state;
    consumptionRecords[groupIndex].records[index].checked = !consumptionRecords[groupIndex].records[index].checked;
    selectedSum += consumptionRecords[groupIndex].records[index].checked ? 1 : -1;
    let groupStatus = true;
    consumptionRecords[groupIndex].records.map(record => {
      groupStatus = groupStatus && record.checked;
    });
    consumptionRecords[groupIndex].checked = groupStatus;
    this.setState({ consumptionRecords, selectedSum });
  };

  handleOk = (type) => {
    let { consumptionRecords } = this.state; // 已加载的所有的公务卡明细，以月份分组
    const { businessCardConsumptions, invoiceOID } = this.props; // 点击确定之前已有的已勾选的公务卡明细，有可能有的公务卡明细还没有加载出来
    let result = [];
    let checkedRecords = this.state.cardList;
    const showRecordsIds = []
    consumptionRecords.map(group => {
      group.records.map(record => {
        showRecordsIds.push(record.id)
        if (record.relationMap) {
          // console.log('record', record)
          const keys = Object.keys(record.relationMap)
          const WAITArr = [] // 待拆分-公务卡明细数组
          const INVOICEArr = [] // 已关联费用-公务卡明细数组
          const NONEArr = [] // 已拆分-公务卡明细数组
          keys.map((key) => {
            if (record.relationMap[key] && record.relationMap[key].length > 0) {
              record.relationMap[key].map((relation) => {
                if (relation.checked) {
                  switch (key) {
                    case 'NONE':
                      NONEArr.push(relation)
                      break
                    case 'INVOICE':
                      INVOICEArr.push(relation)
                      break
                    case 'WAIT':
                      WAITArr.push(relation)
                      break
                    default:
                      break
                  }
                }
              })
            }
          })
          record.checkedRelation = {}
          if (NONEArr && NONEArr.length > 0) {
            record.checkedRelation.NONE = NONEArr
          }
          if (INVOICEArr && INVOICEArr.length > 0) {
            record.checkedRelation.INVOICE = INVOICEArr
          }
          if (WAITArr && WAITArr.length > 0) {
            record.checkedRelation.WAIT = WAITArr
          }
        }
        /**
         * return 0 // 待拆分、已拆分、已关联公务卡明细数量为0
         * return 1 // 已勾选数量为0
         * return 2 // 待拆分、已拆分、已关联公务卡明细被全选
          * return 3 // 部分勾选
         */
        const checkedRes = this.validateAllChecked(record);
        [2, 3].includes(checkedRes) && result.push({
          id: record.id,
          relationMap: record.checkedRelation,
          posCurCod: record.posCurCod,
          oriCurCod: record.oriCurCod,
          // createDate: record.posDate
          createDate: moment(record.trsDate).format('YYYY-MM-DD'),
          trxTim: record.trxTim,
          oriCurAmt: record.oriCurAmt,
          posCurAmt: record.posCurAmt
        });
      })
    });
    // 由于点击保存之前就与该费用关联的公务卡消费很有可能没有加载，所以要处理一下
    // 把没有被加载出来的已关联的公务卡也放到result里进行保存
    businessCardConsumptions.map((selectedRecord) => {
      // console.log('selectedRecord', selectedRecord)
      if (!showRecordsIds.includes(selectedRecord.id)) { // 处理没有被加载出来的已关联或已选的公务卡数据
        if (!selectedRecord.relationMap) {
          selectedRecord.relationMap = {}
        }
        const checkedINVOICE = []
        const checkedNONE = []
        const checkedWAIT = []
        if (selectedRecord.relationMap.NONE) {
          selectedRecord.relationMap.NONE.map((relation) => {
            if (relation.checked) {
              checkedNONE.push(relation)
            }
          })
        }
        if (selectedRecord.relationMap.WAIT) {
          selectedRecord.relationMap.WAIT.map((relation) => {
            if (relation.checked) {
              checkedWAIT.push(relation)
            }
          })
        }
        if (selectedRecord.relationMap.INVOICE) {
          selectedRecord.relationMap.INVOICE.map((relation) => {
            if (relation.checked) {
              checkedINVOICE.push(relation)
            }
          })
        }
        result.push({
          id: selectedRecord.id,
          // createDate: selectedRecord.posDate,
          createDate: moment(selectedRecord.trsDate).format('YYYY-MM-DD'),
          relationMap: {
            INVOICE: checkedINVOICE,
            NONE: checkedNONE,
            WAIT: checkedWAIT
          },
          oriCurCod: selectedRecord.oriCurCod,
          posCurCod: selectedRecord.posCurCod,
          trxTim: selectedRecord.trxTim,
          oriCurAmt: selectedRecord.oriCurAmt,
          posCurAmt: selectedRecord.posCurAmt
        })
      }
    })
    // 2020-12-17 滴滴打车生成的费用只能关联一条公务卡消费记录
    if (type === 'single') { // 公务卡记录只能单选
      if (result.length > 1) {
        message.error('此费用只能关联一条公务卡消费记录');
        return false
      }
    }
    this.props.onSelect(checkedRecords, result, type);
  };

  formatTime = (trxTim) => {
    return `${trxTim.substr(0,2)}:${trxTim.substr(2,2)}:${trxTim.substr(4,2)}`
  };

  /**
  * 格式化数字
  * @param {Number} nStr 数字
  */
  addCommas = (nStr) => {
    nStr = Number(nStr || '0').toFixed(2)
    nStr = nStr + '';
    const x = nStr.split('.');
    let x1 = x[0];
    const x2 = x.length > 1 ? '.' + x[1] : '';
    const rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1,$2');
    }
    return x1 + x2;
  }

  /**
   * 点击展开或收起公务卡消费明细
   * @param {Object} record 一整条公务卡消费记录
   * @param {Number} recordIndex 公务卡消费记录在整月的公务卡消费记录中排第几
   * @param {Number} groupIndex 公务卡消费记录所属的月份，在所有月份中排第几
   */
  hanldeOnViewDetails = (record, recordIndex, groupIndex) => {
    const consumptionRecords = deepFullCopy(this.state.consumptionRecords)
    try {
      const group = consumptionRecords[groupIndex] || {}
      if (group.records && group.records.length > 0) {
        if ((group.records)[recordIndex].id === record.id) {
          consumptionRecords[groupIndex].records[recordIndex].showDetails = !consumptionRecords[groupIndex].records[recordIndex].showDetails
        }
      }
      this.setState({
        consumptionRecords
      })
    } catch (err) {
      message.error('数据问题，查看明细失败')
    }
  }

  /**
   * 点击公务卡消费明细前的checkbox触发
   * @param {Object} e
   * @param {*} relationIndex
   * @param {*} recordIndex
   * @param {*} groupIndex
   * @param {*} relation
   */
  handleOnCheckboxChange = (e, relationIndex, recordIndex, groupIndex, relation, type) => {
    const consumptionRecords = deepFullCopy(this.state.consumptionRecords)
    let { selectedSum } = this.state
    let oriCurCod = null
    if (this.state.consumptionRecords[0] && this.state.consumptionRecords[0].records) {
      if (this.state.consumptionRecords[0].records.length > 0) {
        this.state.consumptionRecords[0].records.some((record) => {
          if (!record.relationMap) {
            record.relationMap = {}
          }
          const keys = Object.keys(record.relationMap)
          keys.some((key) => {
            if (!record.relationMap[key]) {
              record.relationMap[key] = []
            }
            record.relationMap[key].some((relation) => {
              if (relation.checked) {
                oriCurCod = relation.oriCod
                return true
              }
            })
            if (oriCurCod && oriCurCod.length > 0) {
              return true
            }
          })
          if (oriCurCod && oriCurCod.length > 0) {
            return true
          }
        })
      }
    }
    if (oriCurCod && oriCurCod.length > 0) {
      if (relation.oriCod !== oriCurCod) {
        message.error('请选择相同币种的消费记录')
        return false
      }
    }
    try {
      const group = consumptionRecords[groupIndex] || {}
      if (relation.amount !== 0) {
        consumptionRecords[groupIndex].records[recordIndex].relationMap[type][relationIndex].checked = e.target.checked
        if (e.target.checked) {
          selectedSum++
        } else {
          selectedSum--
        }
      }
      const record = consumptionRecords[groupIndex].records[recordIndex]
      const checkedRes = this.validateAllChecked(record)
      switch (checkedRes) {
        case 0:
        case 1:
        case 3:
          consumptionRecords[groupIndex].records[recordIndex].checked = false
          break
        case 2:
          consumptionRecords[groupIndex].records[recordIndex].checked = true
          break
      }
      this.setState({
        consumptionRecords,
        selectedSum,
        businessCardLoading: true
      }, () => {
        this.countRecords()
      })
    } catch (error) {
      message.error('数据问题，勾选失败')
    }
  }

  /**
   * 检查这条公务卡数据中可选的公务卡消费明细是否全选
   * @param {Object} record 一条完整的公务卡数据
   * return 0 // 待拆分、已拆分、已关联公务卡明细数量为0
   * return 1 // 已勾选数量为0
   * return 2 // 待拆分、已拆分、已关联公务卡明细被全选
   * return 3 // 部分勾选
   */
  validateAllChecked = (record) => {
    const relationMap = record.relationMap || {}
    const keys = Object.keys(relationMap)
    let total = 0
    let checked = 0
    keys.map((key) => { // 判断这个公务卡的公务卡明细是否被全选
      if (key === 'INVOICE') {
        relationMap[key].map((relation) => {
          if (relation.artInvoiceOid === this.props.invoiceOID) {
            total++
            if (relation.checked) {
              checked++
            }
          }
        })
      } else if (['WAIT', 'NONE'].includes(key)) {
        relationMap[key].map((relation) => {
          if (relation.amount !== 0) {
            total++
            if (relation.checked) {
              checked++
            }
          }
        })
      }
    })
    if (total === 0) {
      return 0 // 待拆分、已拆分、已关联公务卡明细数量为0
    }
    if (checked === 0) {
      return 1 // 已勾选数量为0
    }
    if (total === checked) { // 全选
      return 2 // 待拆分、已拆分、已关联公务卡明细被全选
    }
    return 3 // 部分勾选
  }

  /**
   * 点击公务卡的全选按钮触发
   * @param {Object} e
   * @param {Object} record
   * @param {Number} recordIndex
   * @param {Number} groupIndex
   */
  handleOnSelectedAll = (e, record, recordIndex, groupIndex) => {
    const consumptionRecords = deepFullCopy(this.state.consumptionRecords)
    let { selectedSum } = this.state
    let oriCurCod = null
    if (this.state.consumptionRecords[0] && this.state.consumptionRecords[0].records) {
      if (this.state.consumptionRecords[0].records.length > 0) {
        this.state.consumptionRecords[0].records.some((record) => {
          if (!record.relationMap) {
            record.relationMap = {}
          }
          const keys = Object.keys(record.relationMap)
          keys.some((key) => {
            if (!record.relationMap[key]) {
              record.relationMap[key] = []
            }
            record.relationMap[key].some((relation) => {
              if (relation.checked) {
                oriCurCod = relation.oriCod
                return true
              }
            })
            if (oriCurCod && oriCurCod.length > 0) {
              return true
            }
          })
          if (oriCurCod && oriCurCod.length > 0) {
            return true
          }
        })
      }
    }
    if (oriCurCod && oriCurCod.length > 0) {
      if (record.oriCurCod !== oriCurCod && e.target.checked) {
        message.error('请选择相同币种的消费记录')
        return false
      }
    }
    try {
      const group = consumptionRecords[groupIndex] || {}
      const keys = Object.keys(consumptionRecords[groupIndex].records[recordIndex].relationMap)
      consumptionRecords[groupIndex].records[recordIndex].checked = e.target.checked
      keys.map((key) => {
        ((consumptionRecords[groupIndex]).records)[recordIndex].relationMap[key].map((relation) => {
          if (['NONE', 'WAIT'].includes(key)) { // 待拆分和已拆分直接根据全选来确定是否
            if (relation.amount !== 0) {
              if (relation.checked !== e.target.checked) {
                if (e.target.checked) {
                  selectedSum++
                } else {
                  selectedSum--
                }
              }
              relation.checked = e.target.checked
            }
          } else if (key === 'INVOICE') {
            if (relation.artInvoiceOid === this.props.invoiceOID) { // 转费用的公务卡明细只有费用oid和当前费用的一致才能控制它的checked
              if (relation.amount !== 0) {
                if (relation.checked !== e.target.checked) {
                  if (e.target.checked) {
                    selectedSum++
                  } else {
                    selectedSum--
                  }
                }
                relation.checked = e.target.checked
              }
            }
          }
        })
      })
      this.setState({
        consumptionRecords,
        selectedSum,
        businessCardLoading: true
      }, () => {
        this.countRecords()
      })
    } catch (error) {
      console.log(error)
      message.error('数据问题，全选失败')
    }
  }

  /**
   * 对公务卡消费明细进行计算，得出所有的被勾选的公务卡数目和被勾选的公务卡明细的总金额
   */
  countRecords = () => {
    const { consumptionRecords } = this.state
    const { businessCardConsumptions, actualCurrencyRate, currencyCode } = this.props;
    let checkedNum = 0
    const showRecordsIds = []
    const checkedRecords = []
    consumptionRecords.map((group) => {
      group.records.map((record) => {
        showRecordsIds.push(record.id)
        // 0 待拆分、已拆分、已关联公务卡明细数量为0
        // 1 已勾选数量为0
        // 2 待拆分、已拆分、已关联公务卡明细被全选
        // 3 部分勾选
        const checkedRes = this.validateAllChecked(record)
        if (checkedRes === 2 || checkedRes === 3) {
          checkedRecords.push(record)
        }
      })
    })
    businessCardConsumptions.map((record) => {
      if (!showRecordsIds.includes(record.id)) {
        checkedRecords.push(record)
      }
    })
    this.setState({
      cardList: checkedRecords
    })
    let oriTotalAmount = 0
    let oriCurCod = ''
    if (checkedRecords.length > 0) {
      checkedRecords.map((record) => {
        if (!record.relationMap) {
          record.relationMap = {}
        }
        const keys = Object.keys(record.relationMap)
        keys.map((key) => {
          (record.relationMap[key] || []).map(relation => {
            if (relation.checked) {
              oriTotalAmount = oriTotalAmount + relation.oriAmount
              checkedNum++
            }
            if (!oriCurCod || oriCurCod.length === 0) {
              oriCurCod = relation.oriCod
            }
          })
        })
      })
      const params = {
        bankTransactions: checkedRecords,
        currencyRate: actualCurrencyRate,
        currencyCode: currencyCode
      }
      baseService.getBusinessCardTotalAmount(params).then((res) => {
        if (res.data.success) {
          const totalAmount = Number(res.data.rows.totalAmount || 0)
          this.setState({
            checkedAmount: totalAmount,
            checkedOriAmount: oriTotalAmount,
            oriCurCod,
            checkedNum,
            businessCardLoading: false
          })
        }
      })
    } else {
      this.setState({
        checkedAmount: 0,
        checkedOriAmount: oriTotalAmount,
        oriCurCod,
        checkedNum: 0,
        businessCardLoading: false
      })
    }
  }

  render() {
    const { loading, consumptionRecords, selectedSum, hasMore, checkedAmount, checkedOriAmount, oriCurCod, checkedNum, businessCardLoading } = this.state;
    const { isBusinessCardMore, currencyCode } = this.props;
    return (
      <div className="business-card-consumption-selector">
          <div className="business-card-container">
        <Spin spinning={businessCardLoading}>
            {consumptionRecords.length > 0 ? consumptionRecords.map((group, groupIndex) => {
              return <div className={'month-group'} key={groupIndex}> {/** 按月分组 */}
                {
                  group.records.map((record, recordIndex) => {
                    if (!record.relationMap) {
                      return null;
                    }
                    let checkBoxAllProps  = {}
                    // 0 待拆分、已拆分、已关联公务卡明细数量为0
                    // 1 已勾选数量为0
                    // 2 待拆分、已拆分、已关联公务卡明细被全选
                    // 3 部分勾选
                    const checkedRes = this.validateAllChecked(record)
                    switch (checkedRes) {
                      case 0:
                        checkBoxAllProps = {
                          disabled: true,
                          checked: record.checked,
                          style: { marginRight: '10px', position: 'relative', bottom: '47px', left: '0px'  },
                          onChange: (e) => this.handleOnSelectedAll(e, record, recordIndex, groupIndex)
                        }
                        break
                      case 1:
                      case 2:
                        checkBoxAllProps = {
                          disabled: !record.posCurAmt || Number(record.posCurAmt) === 0,
                          checked: record.checked,
                          style: { marginRight: '10px', position: 'relative', bottom: '47px', left: '0px'  },
                          onChange: (e) => this.handleOnSelectedAll(e, record, recordIndex, groupIndex)
                        }
                        break
                      case 3:
                        checkBoxAllProps = {
                          indeterminate: true,
                          disabled: !record.posCurAmt || Number(record.posCurAmt) === 0,
                          checked: record.checked,
                          style: { marginRight: '10px', position: 'relative', bottom: '47px', left: '0px' },
                          onChange: (e) => this.handleOnSelectedAll(e, record, recordIndex, groupIndex)
                        }
                        break
                    }
                    return <div key={record.id} className={'bank-bill-item'}> {/** 一整个公务卡 */}
                      <div style={{ borderBottom: record.showDetails ? '1px solid #CDD7EC' : '0px', height: '75px', lineHeight: '25px', fontSize: '12px' }} className={'head-line'}>
                        <div className={'head-line-info'}>
                          <Checkbox
                            {...checkBoxAllProps}
                          />
                          <div style={{ display: 'inline-block', width: 'calc(100% - 40px)' }}>
                            <span>剩余金额： {record.oriCurCod || '-'}&nbsp;{this.addCommas((record.oriCurAmt || 0) - (record.oriAssociatedAmt || 0) + (record.oriCurInvoiceAmt || 0))}</span>
                            <span style={{ marginRight: '5px', marginLeft: '5px' }}>|</span>
                            <span>已处理金额： {record.oriCurCod || '-'}&nbsp;{this.addCommas(record.oriAssociatedAmt || '0')}</span>
                            <br/>
                            <div
                              style={{
                                height: '25px',
                                width: '100%',
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                marginBottom: '-25px'
                              }}
                            >
                            <Popover placement={'topLeft'} content={record.acpName}>
                              <span>交易摘要： {record.acpName || '-'}</span>
                            </Popover>
                            </div>
                            <br/>
                            <span>交易日期：{record.trsDate && record.trsDate.length > 0 ? moment(record.trsDate).format('YYYY-MM-DD') : '-'}</span>
                          </div>
                        </div>
                        {!record.showDetails ? <Icon
                          onClick={() => this.hanldeOnViewDetails(record, recordIndex, groupIndex)}
                          className={'view-details-icon'}
                          type="down-circle-o"
                        /> : <Icon
                          onClick={() => this.hanldeOnViewDetails(record, recordIndex, groupIndex)}
                          className={'view-details-icon'}
                          type="up-circle-o"
                        />}
                      </div>
                      {/** 公务卡--公务卡明细--已拆分 */}
                      {record.showDetails ? record.relationMap.NONE && record.relationMap.NONE.map((relation, relationIndex) => {
                        if (relation.amount === 0) {
                          return null
                        }
                        return (
                          <div className={'relation-line'}>
                            <div className={'relation-content-line'}>
                              <div className={'checkbox-container'}>
                                <Checkbox checked={relation.checked}
                                  disabled={relation.amount === 0}
                                  checked={relation.checked}
                                  style={{ marginRight: '10px' }}
                                  className={'checkBox'}
                                  onChange={(e) => this.handleOnCheckboxChange(e, relationIndex, recordIndex, groupIndex, relation, 'NONE')}
                                />
                              </div>
                              <div className={'info-container'}>
                                <div className={'part'}>
                                  <span className={'label'}>拆分金额：</span>
                                  <span className={'value'}>{record.oriCurCod || '-'}{this.addCommas(relation.oriAmount || '0')}</span>
                                </div>
                                <div className={'part'}>
                                  <span className={'label'}>入账金额：</span>
                                  <span className={'value'}>{record.posCurCod || '-'}{this.addCommas(relation.amount || '0')}</span>
                                </div>
                                <div className={'part'}>
                                  <span className={'label'}>状态：</span>
                                  <span className={'value blue'}>已拆分</span>
                                </div>
                              </div>
                            </div>
                          </div>
                        )
                      }) : null}
                      {/** 公务卡--公务卡明细--已经和此费用关联 */}
                      {record.showDetails ? record.relationMap.INVOICE && record.relationMap.INVOICE.map((relation, relationIndex) => {
                        if (relation.artInvoiceOid !== this.props.invoiceOID) {
                          return null
                        }
                        if (relation.amount === 0) {
                          return null
                        }
                        return (
                          <div className={'relation-line'}>
                            <div className={'relation-content-line'}>
                              <div className={'checkbox-container'}>
                                <Checkbox
                                  disabled={relation.amount === 0}
                                  checked={relation.checked}
                                  style={{ marginRight: '10px' }}
                                  onChange={(e) => this.handleOnCheckboxChange(e, relationIndex, recordIndex, groupIndex, relation, 'INVOICE')}
                                  className={'checkBox'}
                                />
                              </div>
                              <div className={'info-container'}>
                                <div className={'part'}>
                                  <span className={'label'}>拆分金额：</span>
                                  <span className={'value'}>{record.oriCurCod || '-'}{this.addCommas(relation.oriAmount || '0')}</span>
                                </div>
                                <div className={'part'}>
                                  <span className={'label'}>入账金额：</span>
                                  <span className={'value'}>{record.posCurCod || '-'}{this.addCommas(relation.amount || '0')}</span>
                                </div>
                                <div className={'part'}>
                                  <span className={'label'}>状态：</span>
                                  <span className={'value blue'}>转费用</span>
                                </div>
                              </div>
                            </div>
                          </div>
                        )
                      }) : null}
                      {/** 公务卡--公务卡明细--待拆分 */}
                      {record.showDetails ? record.relationMap.WAIT && record.relationMap.WAIT.map((relation, relationIndex) => {
                        if (relation.amount === 0) {
                          return null
                        }
                        return (
                          <div className={'relation-line'}>
                            <div className={'relation-content-line'}>
                              <div className={'checkbox-container'}>
                                <Checkbox checked={relation.checked}
                                  disabled={relation.amount === 0}
                                  checked={relation.checked}
                                  style={{ marginRight: '10px' }}
                                  onChange={(e) => this.handleOnCheckboxChange(e, relationIndex, recordIndex, groupIndex, relation, 'WAIT')}
                                  className={'checkBox'}
                                />
                              </div>
                              <div className={'info-container'}>
                                <div className={'part'}>
                                  <span className={'label'}>待拆分金额：</span>
                                  <span className={'value'}>{record.oriCurCod || '-'}&nbsp;{this.addCommas(relation.oriAmount || '0')}</span></div>
                                <div className={'part'}>
                                  <span className={'label'}>入账金额：</span>
                                  <span className={'value'}>{record.posCurCod|| '-'}&nbsp;{this.addCommas(relation.amount || '0')}</span>
                                </div>
                                <div className={'part'}>
                                  <span className={'label'}>状态：</span>
                                  <span className={'value blue'}>待拆分</span>
                                </div>
                              </div>
                            </div>
                          </div>
                        )
                      }) : null}
                    </div>
                  })
                }
              </div>
              // 2020-12-11 修改公务卡选择整个页面布局，注释掉旧代码
              // <div key={groupIndex}>
              //   <Row className="business-card-group-item" onClick={() => this.handleCheckGroup(groupIndex)}>
              //     <Col span={2}><Checkbox checked={group.checked}/></Col>
              //     <Col span={22}>{messages('components.key780',{arg1:group.month})/*{arg1}月账单*/}<span className="ant-divider"/>{group.startDate} ~ {group.endDate}</Col>
              //   </Row>
              //   {group.records.map((record, index) => (
              //     <Row className="business-card-item" key={record.id} onClick={() => this.handleCheckItem(groupIndex, index)}>
              //       <Col span={2}>
              //         <Checkbox checked={record.checked}/>
              //       </Col>
              //       <Col span={14}>
              //         <div className="business-card-info business-card-item-time">
              //           {record.trsDate} {this.formatTime(record.trxTim)}{record.overTime && <span className="overtime">{messages('components.key781')/*已逾期*/}</span>}
              //           </div>
              //         <div className="business-card-info business-card-item-acp">{record.acpName}</div>
              //       </Col>
              //       <Col span={8}>
              //         <div className="business-card-info business-card-item-bank">{record.bankName} {record.crdNum.substr(record.crdNum.length - 4, 4)}</div>
              //         <div className="business-card-info business-card-item-amount">{record.posCurCod} {record.posCurAmt.toFixed(2)}</div>
              //       </Col>
              //     </Row>
              //   ))}
              // </div>
            }) : !loading ? <div className="no-business-card-consumption">这里空空如也</div> : null}
              {loading ? <div className="loading-footer"><Spin spinning={loading}/></div> : (
                hasMore ?
                  <div className="loading-footer">
                    <div onClick={this.getList}>
                      <Icon type="plus-square-o" />
                      &nbsp;&nbsp;{messages('components.key783')/*加载更多*/}
                    </div>
                  </div> : null
              )}
        </Spin>
          </div>
        <div className="slide-footer" style={{ textAlign: 'left' }}>
          <span>
            已选中
            &nbsp;<span style={{ fontWeight: 'bold' }}>{checkedNum}</span>&nbsp;
              笔，合计&nbsp;
              <span style={{ fontWeight: 'bold' }}>{oriCurCod}&nbsp;
              {this.addCommas(checkedOriAmount)}
            </span>
            <span>/</span>
            <span style={{ fontWeight: 'bold' }}>
              {currencyCode}&nbsp;
              {this.addCommas(checkedAmount)}
            </span>
          </span>
          <div style={{ position: 'absolute', left: '400px', top: '0px' }}>
            <Condition>
              <If value={isBusinessCardMore}>
                <Button
                  onClick={() => this.handleOk('single')}
                  type="primary"
                  disabled={selectedSum < 2}>
                  {`分别生成（${selectedSum}笔）`}
                </Button>
                <Button
                  onClick={() => this.handleOk('more')}
                  type="primary"
                  disabled={selectedSum === 0}> {messages('components.key964')/*生成一笔*/}
                </Button>
              </If>
              <Else>
                <Button
                  onClick={() => this.handleOk(this.props.isSingle || 'more')}
                  type="primary"
                  disabled={false}>
                  {messages('common.ok')/*确定*/}
                </Button>
              </Else>
            </Condition>
            <Button onClick={this.props.onCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </div>
      </div>
    )
  }
}

BusinessCardConsumptionSelector.propTypes = {
  onSelect: React.PropTypes.func.isRequired,
  onCancel: React.PropTypes.func,
  ownerOID: React.PropTypes.string, //费用归属人OID
  isBusinessCardMore: React.PropTypes.bool, // 是否展示生成多笔按钮模式
  businessCardConsumptions: React.PropTypes.array,
  invoiceOID: React.PropTypes.string, // 费用OID
  actualCurrencyRate: React.PropTypes.number,
  currencyCode: React.PropTypes.string,
  isSingle: React.PropTypes.string, // 公务卡是否是单选 single：单选 more：多选
  isDidi: React.PropTypes.bool // 是否是滴滴消费关联公务
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

export default connect(mapStateToProps)(BusinessCardConsumptionSelector);
